package com.yexin.qingzhou.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yexin.qingzhou.dto.ConversationDTO;
import com.yexin.qingzhou.entity.ChatHistory;
import com.yexin.qingzhou.entity.ChatMessage;
import com.yexin.qingzhou.exception.BusinessException;
import com.yexin.qingzhou.mapper.ChatHistoryMapper;
import com.yexin.qingzhou.service.ChatHistoryService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ChatHistoryServiceImpl implements ChatHistoryService {
    
    private final ChatHistoryMapper chatHistoryMapper;
    
    public ChatHistoryServiceImpl(ChatHistoryMapper chatHistoryMapper) {
        this.chatHistoryMapper = chatHistoryMapper;
    }
    
    @Override
    public void saveChat(Long userId, ChatMessage message, Long conversationId) {
        ChatHistory history = new ChatHistory();
        history.setUserId(userId);
        history.setRole(message.getRole());
        history.setContent(message.getContent());
        history.setCreateTime(LocalDateTime.now());
        history.setConversationId(conversationId);
        chatHistoryMapper.insert(history);
    }
    
    @Override
    public List<ChatMessage> getHistoryByConversationId(Long conversationId) {
        LambdaQueryWrapper<ChatHistory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChatHistory::getConversationId, conversationId)
               .orderByAsc(ChatHistory::getCreateTime);
        
        return chatHistoryMapper.selectList(wrapper)
                .stream()
                .map(history -> new ChatMessage(history.getRole(), history.getContent()))
                .collect(Collectors.toList());
    }
    
    @Override
    public Long createNewConversation(Long userId) {
        ChatHistory history = new ChatHistory();
        history.setUserId(userId);
        history.setRole("system");
        history.setContent("会话开始");
        history.setCreateTime(LocalDateTime.now());
        Long conversationId = System.currentTimeMillis();
        history.setConversationId(conversationId);
        chatHistoryMapper.insert(history);
        return conversationId;
    }
    
    @Override
    public List<ConversationDTO> getUserConversations(Long userId) {
        // 1. 先获取所有不重复的conversationId
        LambdaQueryWrapper<ChatHistory> distinctWrapper = new LambdaQueryWrapper<>();
        distinctWrapper.select(ChatHistory::getConversationId)
                      .eq(ChatHistory::getUserId, userId)
                      .groupBy(ChatHistory::getConversationId);
        
        List<ChatHistory> distinctConversations = chatHistoryMapper.selectList(distinctWrapper);
        List<ConversationDTO> conversations = new ArrayList<>();

        // 2. 对每个conversationId查询详细信息
        for (ChatHistory conv : distinctConversations) {
            Long conversationId = conv.getConversationId();
            ConversationDTO dto = new ConversationDTO();
            dto.setConversationId(conversationId);
            
            // 获取会话的第一条用户消息作为标题
            LambdaQueryWrapper<ChatHistory> msgWrapper = new LambdaQueryWrapper<>();
            msgWrapper.eq(ChatHistory::getConversationId, conversationId)
                     .eq(ChatHistory::getRole, "user")
                     .orderByAsc(ChatHistory::getCreateTime)
                     .last("LIMIT 1");
            
            ChatHistory firstMsg = chatHistoryMapper.selectOne(msgWrapper);
            if (firstMsg != null) {
                dto.setTitle(firstMsg.getContent());
                dto.setCreateTime(firstMsg.getCreateTime());
            } else {
                dto.setTitle("新对话");
                // 获取系统消息的创建时间
                LambdaQueryWrapper<ChatHistory> sysWrapper = new LambdaQueryWrapper<>();
                sysWrapper.eq(ChatHistory::getConversationId, conversationId)
                         .eq(ChatHistory::getRole, "system")
                         .orderByAsc(ChatHistory::getCreateTime)
                         .last("LIMIT 1");
                ChatHistory sysMsg = chatHistoryMapper.selectOne(sysWrapper);
                if (sysMsg != null) {
                    dto.setCreateTime(sysMsg.getCreateTime());
                }
            }
            
            // 获取最后一条消息的时间作为更新时间
            LambdaQueryWrapper<ChatHistory> lastMsgWrapper = new LambdaQueryWrapper<>();
            lastMsgWrapper.eq(ChatHistory::getConversationId, conversationId)
                         .orderByDesc(ChatHistory::getCreateTime)
                         .last("LIMIT 1");
            
            ChatHistory lastMsg = chatHistoryMapper.selectOne(lastMsgWrapper);
            if (lastMsg != null) {
                dto.setUpdateTime(lastMsg.getCreateTime());
            }
            
            // 获取消息数量
            LambdaQueryWrapper<ChatHistory> countWrapper = new LambdaQueryWrapper<>();
            countWrapper.eq(ChatHistory::getConversationId, conversationId);
            Long count = chatHistoryMapper.selectCount(countWrapper);
            dto.setMessageCount(count.intValue());
            
            conversations.add(dto);
        }
        
        // 按更新时间倒序排序
        conversations.sort((a, b) -> b.getUpdateTime().compareTo(a.getUpdateTime()));
        
        return conversations;
    }
    
    @Override
    public void deleteConversation(Long userId, Long conversationId) {
        // 先验证会话是否属于该用户
        LambdaQueryWrapper<ChatHistory> checkWrapper = new LambdaQueryWrapper<>();
        checkWrapper.eq(ChatHistory::getUserId, userId)
                    .eq(ChatHistory::getConversationId, conversationId);
        
        Long count = chatHistoryMapper.selectCount(checkWrapper);
        if (count == 0) {
            throw new BusinessException("会话不存在或无权限删除");
        }
        
        // 删除该会话的所有消息
        LambdaQueryWrapper<ChatHistory> deleteWrapper = new LambdaQueryWrapper<>();
        deleteWrapper.eq(ChatHistory::getUserId, userId)
                     .eq(ChatHistory::getConversationId, conversationId);
        
        chatHistoryMapper.delete(deleteWrapper);
    }
} 